package br.edu.ifrn.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import br.edu.ifrn.exeption.ClasseDocumentoException;
import br.edu.ifrn.model.ClasseDocumento;
import br.edu.ifrn.model.Usuario;

public class ClasseDocumentoDAO extends AbstractDAO{
	
	public ClasseDocumentoDAO(EntityManager em) {
		AbstractDAO.em = em;
	}

	@Override
	public <E> void remover(E entity){
		ClasseDocumento classeDocumento = (ClasseDocumento) entity;
		try {
			Usuario u = (Usuario) em.createQuery(
					"Select u from Documento u where u.classe.id = "
							+ classeDocumento.getId()).getSingleResult();
			throw new ClasseDocumentoException();
		} catch (NoResultException e) {
			ClasseDocumento c = em.merge(classeDocumento);
			em.remove(c);
		} catch (ClasseDocumentoException e) {
		}
	}
	
	@Override
	public <E> List<E> listar(){
		Query q = em.createQuery("select c from ClasseDocumento c");
		return q.getResultList();
	}
	
	public ClasseDocumento find(Long id) {
		return findById(ClasseDocumento.class, id);
	}
	public boolean isAssociado(Long id){
		try{
			em.createQuery("Select d From Documento d where d.classe.id = " + id).getSingleResult();
			return true;
		}
		catch (NoResultException e) {
			return false;
		}
	}
}
